package com.asset.controller;


import com.asset.common.BaseResponse;
import com.asset.common.ErrorCode;
import com.asset.common.ResultUtils;
import com.asset.model.entity.User;
import com.asset.service.UserService;
import com.asset.utils.JWTUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;

@RestController
public class LoginController {

    @Resource
    private UserService userService;
    @PostMapping("/login")
    public BaseResponse login(@RequestParam("loginName") String loginName,@RequestParam("password") String password) {
        if(loginName == null||loginName==""){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"登录名为空");
        }
        if(password == null||password==""){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"密码为空");
        }

        HashMap<String ,Object> data = new HashMap<>();
        try {
            User user=userService.login(loginName,password);
            System.out.println(user+"123");
            if (user !=null){
                String token = JWTUtil.createToken(String.valueOf(user.getId()));
                System.out.println(user.getId()+"用户id");
                data.put("userToken",token);
                data.put("userName",user.getRealName());
                System.out.println("解析被Jwt的用户id"+JWTUtil.getUserId(token));

            }else{
                return ResultUtils.error(ErrorCode.PARAMS_ERROR,"用户名或密码错误");
            }
        } catch (Exception e) {
            ResultUtils.error(ErrorCode.NOT_FOUND_ERROR);
            e.printStackTrace();

        }
        return ResultUtils.success( data);
    }
}
